package com.dt.app.security.config;

import com.dt.app.api.sys.service.impl.SysUserServiceImpl;
import com.dt.app.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security主核心配置类
 * @author DT
 * @date 2021/6/5 10:31
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserAccessDeniedHandler userAccessDeniedHandler;
    @Autowired
    private UserAuthenticationEntryPoint userAuthenticationEntryPoint;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private CmsTokenFilter cmsTokenFilter;
    @Autowired
    private UserLogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    private SysUserServiceImpl userDetailsService;

    /**
     * 自定义认证处理器
     * @return 认证操作
     */
    @Bean
    public AuthenticationProvider userAuthenticationProvider() {
        return new CmsUserAuthenticationProvider();
    }

    /**
     * 配置自定义认证
     * @param auth AuthenticationManagerBuilder
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth){
        auth.authenticationProvider(userAuthenticationProvider());
    }

    /**
     * 密码加密
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 白名单资源路径
     * @return 返回IgnoreUrlsConfig
     */
    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig() {
        return new IgnoreUrlsConfig();
    }

    /**
     * 权限资源和自定义认证成功和失败管理器
     * @param http HttpSecurity
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 设置白名单不拦截
        for (String url : ignoreUrlsConfig().getUrls()) {
            http.authorizeRequests().antMatchers(url).permitAll();
        }
        // 防止iframe
        http.headers().frameOptions().disable();
        // 自定义权限拦截器JWT过滤器
        http.addFilterBefore(cmsTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 登录配置
        http.formLogin()
                .loginPage("/admin/login")
                .loginProcessingUrl("/api/user/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler);
        // 开启跨域共享，关闭跨越
        http.cors().and().csrf().disable();
        // 配置拦截规则
        http.authorizeRequests()
                // 放行OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 所有请求都需要验证,必须要放在antMatchers路径拦截之后，不然拦截失效
                .anyRequest().authenticated();
        // 异常抛出处理
        http.exceptionHandling()
                .authenticationEntryPoint(userAuthenticationEntryPoint)
                .accessDeniedHandler(userAccessDeniedHandler);
        // 登录退出处理
        http.logout()
                .logoutUrl("/api/user/loginOut")
                .logoutSuccessHandler(logoutSuccessHandler)
                .clearAuthentication(true).permitAll();
        // 会话管理
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
